package com.sh.data.engine.job.admin.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author tinglan.ys
 * @description: 配置xxl数据源 非主数据源
 * @date 2022/6/7 上午10:28
 */
@Configuration
@MapperScan(
    basePackages = "com.sh.data.engine.job.admin.dao",
    sqlSessionTemplateRef = "xxlSqlSessionTemplate")
public class XxlJobDataSourceConfig {

    @Bean(name = "xxlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.xxl")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("xxlSqlSessionFactory")
    public SqlSessionFactory xxlSqlSessionFactory(@Qualifier("xxlDataSource") DataSource dataSource)
        throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(
            new PathMatchingResourcePatternResolver()
                .getResources("classpath:/mybatis-mapper/*Mapper.xml"));
        return sqlSessionFactory.getObject();
    }

    @Bean(name = "xxlSqlSessionTemplate")
    public SqlSessionTemplate xxlSqlSessionTemplate(
        @Qualifier("xxlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
